package UDP;

import java.net.SocketException;
import java.util.Arrays;
import java.net.InetAddress;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.HashMap;

public class Server {
    private static HashMap<String,String> hashMap = new HashMap<>();

    public static void main(String[] args) throws IOException {
        //创建服务端对象，且指定端口号
        DatagramSocket socket = new DatagramSocket(9090);

        //创建数据包对象
        //接收数据的容器的大小,最大发送过来的数据大小不会超过64KB,
        //因此用64KB大小的字节数组来接收数据
        byte[] bytes = new byte[1024*64];
        DatagramPacket packet = new DatagramPacket(bytes,bytes.length);
        while (true) {
            //此时就可以用数据包来接收数据了
            socket.receive(packet);

            //输出数据
            byte[] data = packet.getData();
            //转化为字符串
            String str = new String(data,0,packet.getLength());
            System.out.println(str);
            //放入数据
            putData();
            String ret = process(str);
            if (ret == null){
                System.out.println("您的输入错误!!!");
                ret = "输入错误!!!";
            }
/*            //还可以获取到客户端的IP对象、客户端的IP对象地址、端口号
            InetAddress client = packet.getAddress();
            String address = client.getHostAddress();
            int clientPort = packet.getPort();
            System.out.println("客户端IP地址:" + address + " , " + "客户端端口号:" + clientPort);
            System.out.println("========================");*/
            byte[] sendByte;
            sendByte = ret.getBytes();
            DatagramPacket sendPacket = new DatagramPacket(sendByte, sendByte.length,packet.getAddress(),packet.getPort());
            socket.send(sendPacket);

        }
    }
    private static void putData(){
        hashMap.put("小狗","dog");
        hashMap.put("小猫","cat");
        hashMap.put("小猪","pig");
        hashMap.put("小鱼","fish");
        hashMap.put("小鸟","bird");
    }

    private static String process(String str){
        return hashMap.get(str);
    }
}
